//
//  SelectedConditionViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/25.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "SelectedConditionViewController.h"
#import "LocationCell.h"
#import "AfterSaleCell.h"
@interface SelectedConditionViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;
@property (weak, nonatomic) IBOutlet UILabel *topView;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
@property(nonatomic,copy)NSString *productTypeId;//产品类型
@property(nonatomic,copy)NSString *minPrice;//记录最低价格
@property(nonatomic,copy)NSString *maxPrice;//记录最高价格
@property(nonatomic,copy)NSString *location;//记录发货地

@property(nonatomic,strong)NSMutableDictionary  *backDic;//记录是不是倒叙选中
@property(nonatomic,assign) int isBack;
@property(nonatomic,strong)NSMutableDictionary *mdic;//属性
@property(nonatomic,strong)NSMutableDictionary *sectionDic;//记录某组是否有选中属性
@property(nonatomic,strong)NSMutableDictionary *serviceDic;//服务防重复
@property(nonatomic,assign)BOOL  isNeedToLoadData;
@end

@implementation SelectedConditionViewController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //重置
    [self reset: self.resetBtn];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"selectViewWillDisappear" object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    if(self.isNeedToLoadData){
        self.isNeedToLoadData = NO;
        [self loadData];
    }else{
        //重置
        [self reset: self.resetBtn];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.backDic = [NSMutableDictionary dictionary];
    self.serviceDic = [NSMutableDictionary dictionary];
    self.sectionDic = [NSMutableDictionary dictionary];
    self.mdic = [NSMutableDictionary dictionary];//存放属性值
    self.dataSource =[NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    [self tableViewAndHeaderView];
    //添加手势，点击空白位置收回键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sendNotifaction)];
    [self.view addGestureRecognizer:tap];

    //从左侧页面通过通知传递产品的id
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getProductId:) name:@"productTypeId" object:nil];
    //属性选择通知
//     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(propertySelected:) name:@"propertySelected" object:nil];
      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(propertySelectedSingle:) name:@"propertySelectedSingle" object:nil];
   
    //服务选择通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(service:) name:@"service" object:nil];
  }

//服务选择通知
-(void)service:(NSNotification*)noti{
    NSDictionary *dic = noti.object;
    [self serViceWithDic:dic];
}
-(void)serViceWithDic:(NSDictionary*)dic{
    NSString *str = self.serviceDic[dic[@"key"]];//key是按钮的tag
    if(str.length){//去重复
        [self.serviceDic removeObjectForKey:dic[@"key"]];
    }else{
        [self.serviceDic setObject:dic[@"service"] forKey:dic[@"key"]];
    }
    DLog(@"服务----%@",self.serviceDic);
    
    TagGroupModel *group = self.dataSource[1];
    TagCellModel *model = group.tagArrary[0];
    NSMutableArray *service = [NSMutableArray array];
    NSArray *selectedSer = self.serviceDic.allKeys;
    //将服务添加到数组中  保存时转化为字符串
    for(int i=0;i<selectedSer.count;i++){
        [service addObject:self.serviceDic[selectedSer[i]]];
    }
    model.services = service;
}
//属性选择通知 ---单选
-(void)propertySelectedSingle:(NSNotification*)noti{
    TagCellModel *model = noti.object;
    //更新数据源
    TagGroupModel *group = self.dataSource[model.section];
    TagCellModel *item = group.tagArrary[model.row];
    NSString *setion = [NSString stringWithFormat:@"%zd",model.section];
    if(self.backDic[setion]){
        NSInteger  lastRow = [self.backDic[setion] integerValue];
        if(lastRow>model.row){
            self.isBack = 1;
        }
    }
    NSString * propertyId =model.propertyId;
    NSString *pid = self.sectionDic[setion];
    if(pid.length){
        if([pid isEqualToString:propertyId]){
            [self.mdic removeObjectForKey:pid];
            [self.sectionDic removeObjectForKey:setion];
            item.isSelected = NO;
        }else{
            if(self.isBack==1||self.isBack==0){
                if(self.isBack==1){
                    self.isBack = 2;
                }
                [self.sectionDic setObject:propertyId forKey:setion];
                [self.mdic setObject:propertyId forKey:propertyId];
                item.isSelected = YES;
            }else if(self.isBack==2){
                self.isBack = 0;
                [self.mdic removeObjectForKey:propertyId];
                item.isSelected = NO;
            }
        }
    }else{
        [self.sectionDic setObject:propertyId forKey:setion];
        [self.mdic setObject:propertyId forKey:propertyId];
        item.isSelected = YES;
    }
    //记录row;
    [self.backDic setObject:[NSString stringWithFormat:@"%ld",model.row] forKey:setion];
    DLog(@"--单选属性--%@",self.mdic);
    DLog(@"modelRow:%ld--itemRow:%ld---item.isSelected:%d--",model.row,item.row,item.isSelected);
}


////属性选择通知 ---多选
//-(void)propertySelected:(NSNotification*)noti{
//    TagCellModel *model = noti.object;
//    TagGroupModel *group = self.dataSource[model.section];
//    NSString *setion = [NSString stringWithFormat:@"%ld",model.section];
//    NSMutableArray *setionArr = self.sectionDic[setion];
//    if(setionArr==nil){
//        setionArr = [NSMutableArray array];
//    }
//    NSString * propertyId =model.propertyId;
//    NSString *pid = self.mdic[propertyId];
//    if(pid.length){
//        [self.mdic removeObjectForKey:propertyId];
//        [setionArr removeObject:propertyId];
//    }else{
//        [self.mdic setObject:propertyId forKey:propertyId];
//        [setionArr addObject:propertyId];
//    }
//    if(setionArr.count>0){
//        [self.sectionDic setObject:setionArr forKey:setion];
//    }else{
//        [self.sectionDic removeObjectForKey:setion];
//    }
//    
//      if([group.chooseState intValue]==0){
//        //刷新组的cell
//        NSIndexSet *indexSet=[NSIndexSet indexSetWithIndex:model.section];
//        [self.tableV reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
//        
//    }
//    DLog(@"--属性--%@",self.mdic);
//}


-(void)getProductId:(NSNotification*)noti{
    self.productTypeId = noti.object;
    self.isNeedToLoadData = YES;
  }
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)sendNotifaction{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"selectViewWillDisappear" object:nil];
}

-(void)loadData{
    //2.20点击筛选展示接口
    NSDictionary *paraDic = @{@"productTypeId":self.productTypeId};
    __weak typeof(self)  weakSelf = self;
//    [MBProgressHUD showActivityMessageInWindow:@""];
      [MBProgressHUD  showHUDAddedTo:self.view animated:NO];
    [Tools AFNetworkingRequestTypePostWithUrl:SHOWPRODUCTBASICPROPERTY paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"点击筛选展示------%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                [MBProgressHUD hideHUDForView:weakSelf.view animated:NO];
                return ;
            }
            if(weakSelf.dataSource.count){
                [weakSelf.dataSource removeAllObjects];
            }
            //发货地
            [weakSelf loadFirstTowSectionData];
            
            for(NSDictionary *typeDic in listArr){
                TagGroupModel *group = [[TagGroupModel alloc]init];
                 group.isOpen = NO;
                group.sessionName =typeDic[@"name"];
                NSArray *content = typeDic[@"values"];
                NSMutableArray *tagArray = [NSMutableArray array];
                for(NSDictionary *dic in content){
                    TagCellModel *model = [[TagCellModel alloc]init];
                    model.name = dic[@"value"];
                    model.propertyId = dic[@"id"];
                    model.section = weakSelf.dataSource.count;
                    [tagArray addObject:model];
                }
                group.tagArrary = tagArray;
                [weakSelf.dataSource addObject:group];
            }
//            [weakSelf loadFirstTowSectionData];
            [weakSelf.tableV reloadData];
            [MBProgressHUD hideHUDForView:weakSelf.view animated:NO];
        }else{
           [MBProgressHUD hideHUDForView:weakSelf.view animated:NO];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)loadFirstTowSectionData{
    TagGroupModel *group = [[TagGroupModel alloc]init];
    group.sessionName = @"价格区间";
    group.isOpen = YES;
    NSMutableArray *m1 = [NSMutableArray array];
    TagCellModel *model = [[TagCellModel alloc]init];
    model.section = 0;
    [m1 addObject:model];
    group.tagArrary = m1;
    [self.dataSource addObject:group];
    
    //发货地
    [self addServiceSetion];
   
}
-(void)addServiceSetion{
    TagGroupModel *group = [[TagGroupModel alloc]init];
    group.sessionName = @"售后保障信息";
    NSMutableArray *m1 = [NSMutableArray array];
    TagCellModel *model =[[TagCellModel alloc]init];
    model.section = 1;
    [m1 addObject:model];
    group.tagArrary = m1.copy;
     [self.dataSource addObject:group];
}

- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, Main_Screen_Width, Main_Screen_Height-49-self.topView.bottom) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = [UIColor whiteColor];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;    {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    TagGroupModel *group = self.dataSource[section];
    if(!group.isOpen){
        return 0;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)  weakSelf = self;
    if(indexPath.section==0){//选择价格区间
    TagCell *tagCell =   [[[NSBundle mainBundle]loadNibNamed:@"TagCell" owner:self options:nil]lastObject];
        tagCell.minBlock = ^(NSString *minPrice){//最低价格
            weakSelf.minPrice = minPrice;
            DLog(@"---min  --%@",minPrice);
        };
        tagCell.maxBlock = ^(NSString *maxPrice){//最高价格
            weakSelf.maxPrice = maxPrice;
            DLog(@"---max  --%@",maxPrice);
        };
        tagCell.minPriceTextField.text = self.minPrice;
        tagCell.maxPriceTextField.text = self.maxPrice;
        return tagCell;
    }
    if(indexPath.section==1){//选择服务
//        LocationCell  *cell =   [[[NSBundle mainBundle]loadNibNamed:@"LocationCell" owner:self options:nil]lastObject];
//        cell.cityNameBlock = ^(NSString *cityName) {
//            weakSelf.location = cityName;
//        };
//        cell.locationBlock = ^{
//        //定位
//            
//        };
        AfterSaleCell   *cell=[[[NSBundle mainBundle]loadNibNamed:@"AfterSaleCell" owner:self options:nil]lastObject];
        TagGroupModel *group = self.dataSource[indexPath.section];
        cell.model = group.tagArrary[indexPath.row];
        return cell;
    }
    NSString *ident=@"actell";
    ButtonCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"ButtonCell" owner:self options:nil]lastObject];
    }
    TagGroupModel *model = self.dataSource[indexPath.section];
    cell.model = model;
    return cell;
}

//自定义头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *headID = @"SilderHead";
    SilderHead *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if(headView==nil){
        headView = [[[NSBundle mainBundle]loadNibNamed:@"SilderHead" owner:self options:nil]lastObject];
    }
    TagGroupModel *model = self.dataSource[section];
    headView.tagGroupModel =model;
    headView.tag = section +200;
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [headView addGestureRecognizer:tapGesture];
    return headView;
}

//点击组的头视图展开和收起列表
-(void)tapAction:(UITapGestureRecognizer*)tap
{
     [self reloadSetion:tap.view.tag-200];
}

-(void)reloadSetion:(NSInteger)index{
    TagGroupModel *group = self.dataSource[index];
    if(group.isOpen){
        group.isOpen = NO;
    }else{
        group.isOpen = YES;
    }
    //刷新组的cell
    NSIndexSet *indexSet=[NSIndexSet indexSetWithIndex:index];
    [self.tableV reloadSections:indexSet withRowAnimation:UITableViewRowAnimationBottom];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0) return 38;
    if(indexPath.section==1)return 62;
    //根据标签数量计算单元格的高度
    TagGroupModel *model = self.dataSource[indexPath.section];
    int row =0;
    if(model.tagArrary.count%3!=0){
        row=1;
    }
    NSInteger   rows = model.tagArrary.count/3+row;
    return rows*(22+12)+8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;{
    return 30;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"---%ld",indexPath.row);
}
//重置
- (IBAction)reset:(UIButton *)sender {
    //1,//重置标签的状态
    [self resetDatasoure];
    //2,清除价格区间内容[
    [self clearPrice];
    //3,清除位置信息
    //清空全局信息
    [self.serviceDic removeAllObjects];
    [self.sectionDic removeAllObjects];
    [self.mdic removeAllObjects];
    
}
- (void)clearPrice{
    self.minPrice = @"";
    self.maxPrice = @"";
    [[NSNotificationCenter defaultCenter]postNotificationName:@"clearInputText" object:nil];
}

//重置标签的状态
-(void)resetDatasoure{
    
    TagGroupModel *group = self.dataSource[1];
    TagCellModel *model = group.tagArrary[0];
    [model.services removeAllObjects];
    
    for(int i=2;i<self.dataSource.count;i++){
        TagGroupModel *model = self.dataSource[i];
        NSArray *tagArr = model.tagArrary;
        for(int j=0;j<tagArr.count;j++){
            TagCellModel *item = tagArr[j];
            if(item.isSelected){
                item.isSelected = NO;
            }
        }
    }
    
    [self.tableV reloadData];
}

//完成
- (IBAction)complete:(UIButton *)sender {
    if(!self.minPrice.length){
        self.minPrice = @"";
    }
    if(!self.maxPrice.length){
        self.maxPrice = @"";
    }
    NSDictionary *dataDic = @{
                              @"service":[self getServices],
                              @"lowPrice":self.minPrice,
                              @"highPrice":self.maxPrice,
                              @"sendLocation":@"",
                              @"properties":[self getProProetry]
                              };
    NSData *pramasData = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *parameterData = [[NSString alloc]initWithData:pramasData encoding:NSUTF8StringEncoding];
    DLog(@"筛选条件-----%@",parameterData);
    //发送点击了完成按钮的通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"complete" object:parameterData];
}

//获取属性信息
-(NSArray*)getProProetry{
    //3.28添加产品信息接口
    NSMutableArray *parmArr = [NSMutableArray array];
    for(NSString *key in self.mdic){
        [parmArr addObject:self.mdic[key]];
    }
       return parmArr.copy;
}

-(NSString *)getServices{
    NSArray *values = self.serviceDic.allValues;
    if(values.count==0){
        return @"";
    }
    if(values.count==1){
        return values.firstObject;
    }
    NSMutableString *serviceName = [[NSMutableString alloc]init];
    for(int i=0;i<values.count;i++){
        if(i<values.count-1){
            [serviceName appendString:values[i]];
            [serviceName appendString:@","];
        }else{
             [serviceName appendString:values[i]];
        }
    }
    return serviceName;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
        return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
